# -*- coding: utf-8 -*-
# @Time    : 2021/11/13 21:07
# @Author  : travel2040
# @Email   : travel2040@163.com
# @File    : opencv-检测视频流人脸.py
# 需要安装的库
# pip install opencv_python
import cv2
import time

def detectImage(img):

    def is_inside(o, i):
        ox, oy, ow, oh = o
        ix, iy, iw, ih = i
        return ox > ix and oy > iy and ox + ow < ix + iw and oy + oh < iy + ih

    def draw_person(image, person):
        x, y, w, h = person
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2)


    a, b = img.shape[:2]
    img = cv2.resize(img, (a//5, b//5))
    hog = cv2.HOGDescriptor()
    hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

    found, w = hog.detectMultiScale(img)

    found_filtered = []

    for ri, r in enumerate(found):
        for qi, q in enumerate(found):
            if ri != qi and is_inside(r, q):
                break
            else:
                found_filtered.append(r)

    for person in found_filtered:
        draw_person(img, person)

    return img

if __name__ == '__main__':
    address = 'rtsp://admin:a12345678@192.168.0.1'
    cap = cv2.VideoCapture(address)
    fv_num = 0
    while True:
        fv_num += 1
        ret, img = cap.read()
        if ret:
            time_start = time.time()
            img = detectImage(img)
            cv2.imshow('img', img)
            print(fv_num, "detectImage 耗时：", time.time() - time_start, "秒")

            if cv2.waitKey(1) & 0xFF == ord('q'):
                cap.release()
                cv2.destroyAllWindows()
                break